#pragma once

#include <string>
#include <memory>
#include <unordered_map>
#include "order.h"
#include "position.h"

namespace hft {

// 风控检查结果
struct RiskCheckResult {
    bool passed;                 // 是否通过风控检查
    std::string message;        // 风控检查失败原因

    RiskCheckResult(bool p = true, const std::string& msg = "") 
        : passed(p), message(msg) {}
};

// 风控规则基类
class RiskRule {
public:
    virtual ~RiskRule() = default;
    
    // 检查订单是否满足风控规则
    virtual RiskCheckResult checkOrder(const Order& order) = 0;
    
    // 检查持仓是否满足风控规则
    virtual RiskCheckResult checkPosition(const Position& position) = 0;
    
    // 更新风控规则的状态（如更新当日亏损等）
    virtual void update(double pnl, double equity) = 0;
    
    // 重置风控规则状态（如日初重置）
    virtual void reset() = 0;
};

// 最大持仓限制规则
class MaxPositionRule : public RiskRule {
public:
    MaxPositionRule(double maxPositionValue);
    RiskCheckResult checkOrder(const Order& order) override;
    RiskCheckResult checkPosition(const Position& position) override;
    void update(double pnl, double equity) override;
    void reset() override;

private:
    double max_position_value_;
    std::unordered_map<std::string, double> current_positions_;
};

// 最大订单规模规则
class MaxOrderSizeRule : public RiskRule {
public:
    MaxOrderSizeRule(double maxOrderSize);
    RiskCheckResult checkOrder(const Order& order) override;
    RiskCheckResult checkPosition(const Position& position) override;
    void update(double pnl, double equity) override;
    void reset() override;

private:
    double max_order_size_;
};

// 最大杠杆规则
class MaxLeverageRule : public RiskRule {
public:
    MaxLeverageRule(double maxLeverage);
    RiskCheckResult checkOrder(const Order& order) override;
    RiskCheckResult checkPosition(const Position& position) override;
    void update(double pnl, double equity) override;
    void reset() override;

private:
    double max_leverage_;
    double current_equity_;
    std::unordered_map<std::string, double> position_values_;
};

// 最大回撤规则
class MaxDrawdownRule : public RiskRule {
public:
    MaxDrawdownRule(double maxDrawdownPercent);
    RiskCheckResult checkOrder(const Order& order) override;
    RiskCheckResult checkPosition(const Position& position) override;
    void update(double pnl, double equity) override;
    void reset() override;

private:
    double max_drawdown_percent_;
    double peak_equity_;
    double current_equity_;
};

// 最大日亏损规则
class MaxDailyLossRule : public RiskRule {
public:
    MaxDailyLossRule(double maxDailyLoss);
    RiskCheckResult checkOrder(const Order& order) override;
    RiskCheckResult checkPosition(const Position& position) override;
    void update(double pnl, double equity) override;
    void reset() override;

private:
    double max_daily_loss_;
    double daily_pnl_;
    double start_equity_;
};

} // namespace hft